package common

import (
	"net/http"

	"gitee.com/wangshh_123/cross-pay-go/src/database"
	"gitee.com/wangshh_123/cross-pay-go/src/errors"
	"gitee.com/wangshh_123/cross-pay-go/src/models"

	"github.com/gin-gonic/gin"
)

// GetMatrixAccountInfo 从上下文中获取矩阵账户信息
func GetMatrixAccountInfo(ctx *gin.Context) (*models.MatrixAccountInfo, error) {
	matrixInfo, exists := ctx.Get("matrix_account_info")
	if !exists {
		return nil, errors.NewAppError(http.StatusUnauthorized, "matrix_account_not_found", nil)
	}

	matrixAccountInfo, ok := matrixInfo.(*models.UserMatrixAccount)
	if !ok {
		return nil, errors.NewAppError(http.StatusInternalServerError, "matrix_account_invalid", nil)
	}

	return &models.MatrixAccountInfo{
		MatrixAccount:     matrixAccountInfo.MatrixAccount,
		MatrixAccountName: matrixAccountInfo.MatrixAccountName,
		UserID:            matrixAccountInfo.UserID,
	}, nil
}

// UpdateDatabase 更新数据库记录
func UpdateDatabase(table string, updates map[string]interface{}, conditions map[string]interface{}) error {
	query := database.DB.Table(table)
	for key, value := range conditions {
		query = query.Where(key+" = ?", value)
	}
	return query.Updates(updates).Error
}
